package com.yami.shop.security.api.util;

import com.yami.shop.common.util.HttpContextUtils;
import com.yami.shop.security.api.model.YamiSubmitPerson;
import com.yami.shop.security.api.model.YamiUser;
import com.yami.shop.security.comment.exception.UnauthorizedException;
import lombok.experimental.UtilityClass;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;

/**
 * @author LGH
 */
@UtilityClass
public class SecurityUtils {

    private static final String USER_REQUEST = "/sha/p/";

    /**
     * 获取用户
     */
    public YamiUser getUser() {
        if (!HttpContextUtils.getHttpServletRequest().getRequestURI().startsWith(USER_REQUEST) &&
                !HttpContextUtils.getHttpServletRequest().getRequestURI().startsWith("/sha/user/registerOrBindUser")) {
            // 用户相关的请求，应该以/p开头！！！
            throw new RuntimeException("yami.user.request.error");
        }
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if (authentication == null) {
            // 未找到此用户信息
            throw new UnauthorizedException("yami.user.no.exist");
        }

        if (!(authentication instanceof OAuth2Authentication)) {
            // 未找到此用户信息
            throw new UnauthorizedException("yami.user.no.exist");
        }
        OAuth2Authentication oAuth2Authentication = (OAuth2Authentication)authentication;

        YamiUser details = (YamiUser) oAuth2Authentication.getUserAuthentication().getDetails();

        if (details == null) {
            // 未找到此用户信息
            throw new UnauthorizedException("yami.user.no.exist");
        }
        return details;
    }

    public YamiSubmitPerson getSubmitPerson() {
        if (!HttpContextUtils.getHttpServletRequest().getRequestURI().startsWith(USER_REQUEST)) {
            // 用户相关的请求，应该以/p开头！！！
            throw new RuntimeException("yami.user.request.error");
        }
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if (authentication == null) {
            // 未找到此用户信息
            throw new UnauthorizedException("yami.user.no.exist");
        }

        if (!(authentication instanceof OAuth2Authentication)) {
            // 未找到此用户信息
            throw new UnauthorizedException("yami.user.no.exist");
        }
        OAuth2Authentication oAuth2Authentication = (OAuth2Authentication)authentication;

        YamiSubmitPerson details = (YamiSubmitPerson) oAuth2Authentication.getUserAuthentication().getDetails();

        if (details == null) {
            // 未找到此用户信息
            throw new UnauthorizedException("yami.user.no.exist");
        }
        return details;
    }
}
